import React, { useState, useEffect } from 'react';
import { Table, Card, Button, Form, Input, DatePicker, Select, Space, Modal, message } from 'antd';
import type { TablePaginationConfig } from 'antd/es/table';
import { useNavigate } from 'react-router-dom';
import { PlusOutlined, EditOutlined, DeleteOutlined, UploadOutlined, DownloadOutlined } from '@ant-design/icons';
import { getSalaryList, deleteSalary, exportSalaries, getSalaryMonths } from '@/api/salary';
import type { Salary, SalaryQueryParams } from '@/api/salary';
import ImportModal from '@/components/salary/ImportModal';
import dayjs from 'dayjs';

const { RangePicker } = DatePicker;

const initialSearchParams: SalaryQueryParams = {
  current: 1,
  size: 10,
  keyword: '',
  className: '',
  position: '',
  salaryMonth: '',
};

const SalaryList: React.FC = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<Salary[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [importModalVisible, setImportModalVisible] = useState(false);
  const [salaryMonths, setSalaryMonths] = useState<string[]>([]);
  const [searchParams, setSearchParams] = useState<SalaryQueryParams>(initialSearchParams);

  useEffect(() => {
    fetchData();
    fetchSalaryMonths();
  }, [pagination.current, pagination.pageSize, searchParams]);

  const fetchData = async () => {
    try {
      setLoading(true);
      const params: SalaryQueryParams = {
        ...searchParams,
        current: pagination.current,
        size: pagination.pageSize,
      };

      const result = await getSalaryList(params);
      setData(result.records);
      setPagination(prev => ({
        ...prev,
        total: result.total,
      }));
    } catch (error) {
      // 错误已在request.ts中处理
    } finally {
      setLoading(false);
    }
  };

  const fetchSalaryMonths = async () => {
    try {
      const months = await getSalaryMonths();
      setSalaryMonths(months);
    } catch (error) {
      // 错误已在request.ts中处理
    }
  };

  const handleSearch = async () => {
    try {
      const values = await form.validateFields();
      setSearchParams({
        ...initialSearchParams,
        ...values,
        salaryMonth: values.salaryMonth,
      });
      setPagination(prev => ({ ...prev, current: 1 }));
    } catch (error) {
      // 错误已在request.ts中处理
    }
  };

  const handleReset = () => {
    form.resetFields();
    setSearchParams(initialSearchParams);
    setPagination(prev => ({ ...prev, current: 1 }));
  };

  const handleDelete = async (id: number) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这条工资记录吗？',
      onOk: async () => {
        try {
          await deleteSalary(id);
          message.success('删除成功');
          fetchData();
        } catch (error) {
          // 错误已在request.ts中处理
        }
      },
    });
  };

  const handleExport = async () => {
    try {
      const values = await form.validateFields();
      const params: SalaryQueryParams = {
        ...values,
        salaryMonth: values.salaryMonth?.[0]?.format('YYYY-MM'),
      };
      const response = await exportSalaries(params);
      
      // 创建Blob对象
      const blob = new Blob([response], { type: 'application/vnd.ms-excel' });
      
      // 创建下载链接
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `工资数据_${dayjs().format('YYYYMMDDHHmmss')}.xlsx`;
      
      // 触发下载
      document.body.appendChild(link);
      link.click();
      
      // 清理
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      
      message.success('导出成功');
    } catch (error) {
      // 错误已在request.ts中处理
    }
  };

  const columns = [
    {
      title: '所在班级',
      dataIndex: 'className',
      key: 'className',
    },
    {
      title: '职务',
      dataIndex: 'position',
      key: 'position',
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '身份证号',
      dataIndex: 'idCard',
      key: 'idCard',
    },
    {
      title: '标识号',
      dataIndex: 'identifier',
      key: 'identifier',
    },
    {
      title: '工资月份',
      dataIndex: 'salaryMonth',
      key: 'salaryMonth',
      render: (text: string) => text,
    },
    {
      title: '基础工资',
      dataIndex: 'basicSalary',
      key: 'basicSalary',
      render: (value: number | null) => value !== null ? `¥${value.toFixed(2)}` : '-',
    },
    {
      title: '绩效工资',
      dataIndex: 'performanceSalary',
      key: 'performanceSalary',
      render: (value: number | null) => value !== null ? `¥${value.toFixed(2)}` : '-',
    },
    {
      title: '单项奖',
      dataIndex: 'individualBonus',
      key: 'individualBonus',
      render: (value: number | null) => value !== null ? `¥${value.toFixed(2)}` : '-',
    },
    {
      title: '企业年金',
      dataIndex: 'enterprisePension',
      key: 'enterprisePension',
      render: (value: number | null) => value !== null ? `¥${value.toFixed(2)}` : '-',
    },
    {
      title: '养老保险',
      dataIndex: 'endowmentInsurance',
      key: 'endowmentInsurance',
      render: (value: number | null) => value !== null ? `¥${value.toFixed(2)}` : '-',
    },
    {
      title: '失业保险',
      dataIndex: 'unemploymentInsurance',
      key: 'unemploymentInsurance',
      render: (value: number | null) => value !== null ? `¥${value.toFixed(2)}` : '-',
    },
    {
      title: '医疗保险',
      dataIndex: 'medicalInsurance',
      key: 'medicalInsurance',
      render: (value: number | null) => value !== null ? `¥${value.toFixed(2)}` : '-',
    },
    {
      title: '住房公积金',
      dataIndex: 'housingFund',
      key: 'housingFund',
      render: (value: number | null) => value !== null ? `¥${value.toFixed(2)}` : '-',
    },
    {
      title: '个税',
      dataIndex: 'personalTax',
      key: 'personalTax',
      render: (value: number | null) => value !== null ? `¥${value.toFixed(2)}` : '-',
    },
    {
      title: '补扣项一',
      dataIndex: 'deductionOne',
      key: 'deductionOne',
      render: (value: number | null) => value !== null ? `¥${value.toFixed(2)}` : '-',
    },
    {
      title: '补扣项二',
      dataIndex: 'deductionTwo',
      key: 'deductionTwo',
      render: (value: number | null) => value !== null ? `¥${value.toFixed(2)}` : '-',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Salary) => (
        <Space>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => navigate(`/salaries/${record.id}/edit`)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <Card>
      <Form
        form={form}
        layout="inline"
        style={{ marginBottom: 24 }}
      >
        <Form.Item name="keyword" label="关键词">
          <Input placeholder="姓名/身份证号/标识号" allowClear />
        </Form.Item>
        <Form.Item name="className" label="所在班级">
          <Input placeholder="请输入所在班级" allowClear />
        </Form.Item>
        <Form.Item name="position" label="职务">
          <Input placeholder="请输入职务" allowClear />
        </Form.Item>
        <Form.Item name="salaryMonth" label="工资月份">
          <Select
            placeholder="请选择工资月份"
            allowClear
            options={salaryMonths.map(month => ({
              label: month,
              value: month,
            }))}
          />
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" onClick={handleSearch}>
              搜索
            </Button>
            <Button onClick={handleReset}>
              重置
            </Button>
          </Space>
        </Form.Item>
      </Form>

      <div style={{ marginBottom: 16 }}>
        <Space>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => navigate('/salaries/new')}
          >
            新增
          </Button>
          <Button
            icon={<UploadOutlined />}
            onClick={() => setImportModalVisible(true)}
          >
            导入
          </Button>
          <Button
            icon={<DownloadOutlined />}
            onClick={handleExport}
          >
            导出
          </Button>
        </Space>
      </div>

      <Table
        columns={columns}
        dataSource={data}
        rowKey="id"
        loading={loading}
        pagination={pagination}
        onChange={(pagination: TablePaginationConfig) => {
          if (pagination.current && pagination.pageSize) {
            setPagination({
              current: pagination.current,
              pageSize: pagination.pageSize,
              total: pagination.total || 0,
            });
          }
        }}
        scroll={{ x: 1500 }}
      />

      <ImportModal
        open={importModalVisible}
        onCancel={() => setImportModalVisible(false)}
        onSuccess={() => {
          setImportModalVisible(false);
          fetchData();
          fetchSalaryMonths();
        }}
      />
    </Card>
  );
};

export default SalaryList; 